import Vue from "vue";
import Vuex from "vuex";
import {getMenuList} from "@/api"
Vue.use(Vuex);
//引入allRoutes
import allRoutes from "../router/allRoutes"
//引入递归函数
import recursionRoutes from "../utils/recursionRoutes"
//引入动态路由dynamicRoutes
import dynamicRoutes from "../router/dynamicRoutes"
//引入router
import router from "../router"

//刷新页面会丢失用户信息,所以要从localStorage中取
let userInfo = localStorage.getItem("crlm-userinfo") || "{}";
  userInfo = JSON.parse(userInfo)

export default new Vuex.Store({
  state: {
    userInfo,
    menuList:[],//定义侧边栏菜单
    crumbs:[]
  },
  mutations: {
    //更改userInfo
    SET_USERINFO(state,payload){
      state.userInfo = payload
    },
    SET_SIDMENT(state,payload){
      state.menuList = payload
      // console.log(state.menuList);
      //动态的将路由添加到routes中 核心方法 router.addRoutes(符合路由配置规则)要在路由外面套上数组
      //1.将menulist赋值给dynamicRoutes的chiildren
      let target = dynamicRoutes.find(item => item.path === "/")
      target.children = [...state.menuList]
      // 2.动态路由添加到router/routes中
      router.addRoutes(dynamicRoutes)
    },
    //设置面包屑
    SET_CRUMBS(state,payload){
      state.crumbs = payload
    }
  },
  actions: {
    // 在ES7中有个新方法 async声明哪个函数包含异步操作就在前面加上async await是等待异步操作 两个配合起来就会将异步操作变成同步
    async FETCH_MENULIST({commit}){
      //1.发送请求,获取用户菜单数据
      let userMenu = await getMenuList()
      // console.log(userMenu);
      //2.通过allRoutes和请求回来的用户菜单数据进行对比
      let sideMenu = recursionRoutes(allRoutes,userMenu.data.menuList)
      // console.log(sideMenu);
      //3将结果提交给mutation 
      commit("SET_SIDMENT",sideMenu)
    }
  },
  modules: {}
});
